<?php
/**
 * auth WQl
 * 2021/6/16 18:10
 */


namespace service;


use m\BasicM;
use m\SendCodeM;
use m\UserM;

class UserS
{
    use \Singleton;

    public $role = [1=>'admin', 2=>'adminx',3=>'market'];

    /**
     * 用户登录
     * @throws \ApiError
     */
    public function login($info, $pwd, $code, \Req $req): string
    {
        $userId = $req->user_id;
        if ($userId) throw new \ApiError("您已登录");
        $pwd = md5($pwd);
        //校验账号密码
        $userInfo = UserM::getInstance()->login([
            ['pwd','=',$pwd],
            ['info','=',$info]
        ]);
        //校验手机验证码
        try{
            \Db::getInstance()->beginTrans();
            //生成token
            $key = '344'; //key
            $time = time(); //当前时间
            $token = [
                'iss'   => 'admin', //签发者 可选
                'iat'   => $time, //签发时间
                'exp'   => $time + 86400, //24时过期时间
                'data'  => $userInfo,
            ];
            $token = \Firebase\JWT\JWT::encode($token, $key);
            //更新用户登录信息
            UserM::getInstance()->updateUserInfo(['last_time'=>time(),'last_ip'=>$req->_from_ip],"id={$userInfo['id']}");
            \Db::getInstance()->commitTrans();
        } catch (\Throwable $exception) {
            \Db::getInstance()->rollBackTrans();
            throw new \ApiError($exception->getMessage());
        }
        return  $token; //输出Token
    }

}